package com.iseastar.guojiang.newcabinet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.iseastar.BaseActivity2;
import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.loc.BaiduLocationService;
import com.shouhuobao.station.R;

/**
 * Created by joker on 2017/12/19.
 * 地图展示
 */
public class BaiDuMapActivity extends BaseActivity2 implements View.OnClickListener {

    private BaiduMap mBaiduMap;
    private TextureMapView mMapView = null;
    private double lat = 0;
    private double lon = 0;
    private double gdLat = 0;
    private double gdLon = 0;
    private PlanNode sNode = null;
    private PlanNode eNode = null;
    private RoutePlanSearch mSearch;
    private int taskType;//任务类型
    private int type;//同城判断是取还是送  0 取 1 送

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        taskType = getIntent().getIntExtra("taskType", 0);
        lat = getIntent().getDoubleExtra("lat", 0);
        lon = getIntent().getDoubleExtra("lon", 0);
        gdLat = getIntent().getDoubleExtra("gdLat", 0);
        gdLon = getIntent().getDoubleExtra("gdLon", 0);
        type = getIntent().getIntExtra("type", type);
        super.onCreate(savedInstanceState);
        showLoadingDialog("正在定位");
        Intent intent = new Intent();
        intent.setClass(getContext(), BaiduLocationService.class);
        intent.putExtra("msgId", MsgID.get_location_baidu_map);
        startService(intent);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_baidu_map);
        super.findViewById();
        getAppTitle().setCommonTitle("地图");
        mMapView = (TextureMapView) findViewById(R.id.bmapView);
        findViewById(R.id.navigation_tv).setOnClickListener(this);
        findViewById(R.id.close_tv).setOnClickListener(this);
        mBaiduMap = mMapView.getMap();
        //普通地图
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mMapView.showZoomControls(false);//隐藏缩放按钮
        mMapView.showScaleControl(false);//隐藏比例尺
        mBaiduMap.setMyLocationEnabled(true);
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(listener);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.get_location_baidu_map:
                cancelLoadingDialog();
                final BDLocation loc = (BDLocation) msg.obj;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loc == null) {
                            cancelLoadingDialog();
                            showToast("定位失败");
                        } else {
                            String currentCityName = loc.getCity();
                            if (isNotEmpty(currentCityName)) {
                                routeplanToNavi(loc);
                            } else {
                                showToast("定位失败");
                            }
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    private void routeplanToNavi(BDLocation location) {
        mBaiduMap.clear();
        LatLng northeast = new LatLng(Math.max(location.getLatitude(), lat), Math.max(location.getLongitude(), lon));
        LatLng southwest = new LatLng(Math.min(location.getLatitude(), lat), Math.min(location.getLongitude(), lon));
        LatLngBounds bounds = new LatLngBounds.Builder().include(northeast).include(southwest).build();
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(bounds);
        sNode = PlanNode.withLocation(new LatLng(location.getLatitude(), location.getLongitude()));
        eNode = PlanNode.withLocation(new LatLng(lat, lon));

        if (sNode != null && eNode != null) {
            mSearch.bikingSearch((new BikingRoutePlanOption()).from(sNode).to(eNode));
            //            mSearch.drivingSearch((new DrivingRoutePlanOption()).from(sNode).to(eNode));
        }
    }

    OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
        @Override
        public void onGetWalkingRouteResult(WalkingRouteResult result) {
            //获取步行线路规划结果
        }

        @Override
        public void onGetTransitRouteResult(TransitRouteResult result) {
            //获取公交换乘路径规划结果
        }

        @Override
        public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

        }

        @Override
        public void onGetDrivingRouteResult(DrivingRouteResult result) {
            //获取驾车线路规划结果
            //                        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            //                            showToast("抱歉，未找到结果");
            //                        }
            //                        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
            //                            //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
            //                            //result.getSuggestAddrInfo()
            //                            return;
            //                        }
            //                        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            //                            DrivingRouteOverlay overlay = new MyDrivingRouteOverlay(mBaiduMap);//路线覆盖物，MyDrivingRouteOverlay代码下面给出
            //                            //            mBaidumap.setOnMarkerClickListener(overlay);
            //                            overlay.setData(result.getRouteLines().get(0));
            //                            overlay.addToMap();
            //                            overlay.zoomToSpan();
            //                        }
        }

        @Override
        public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

        }

        @Override
        public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
            if (bikingRouteResult == null || bikingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
                showToast("抱歉，未找到结果");
                return;
            }
            if (bikingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                //result.getSuggestAddrInfo()
                return;
            }
            if (bikingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
                BikingRouteOverlay overlay = new MyBikingRouteOverlay(mBaiduMap);//路线覆盖物，MyDrivingRouteOverlay代码下面给出
                //            mBaidumap.setOnMarkerClickListener(overlay);
                overlay.setData(bikingRouteResult.getRouteLines().get(0));
                overlay.addToMap();
                overlay.zoomToSpan();
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_tv:
                finish();
                break;
            //地图导航
            case R.id.navigation_tv:
                DialogMgr.showSelectMapToNavigation(getContext(), findViewById(R.id.navigation_tv), lat, lon, gdLat, gdLon);
                break;
        }
    }

    //定制RouteOverly
    //    private class MyDrivingRouteOverlay extends DrivingRouteOverlay {
    //        /**
    //         * 构造函数
    //         *
    //         * @param baiduMap 该DrivingRouteOvelray引用的 BaiduMap
    //         */
    //        public MyDrivingRouteOverlay(BaiduMap baiduMap) {
    //            super(baiduMap);
    //        }
    //
    //        @Override
    //        public BitmapDescriptor getStartMarker() {
    //            //覆写此方法以改变默认起点图标
    //            return BitmapDescriptorFactory.fromResource(R.drawable.map_me);
    //            //这里可以使用BitmapDescriptorFactory.fromView(view)实现自定义view覆盖物，自定义覆盖物请关注以后的文章。
    //        }
    //
    //        @Override
    //        public int getLineColor() {
    //            // TODO Auto-generated method stub
    //            //覆写此方法以改变默认绘制颜色
    //            //Returns:
    //            //线颜色
    //            return super.getLineColor();
    //        }
    //
    //        @Override
    //        public BitmapDescriptor getTerminalMarker() {
    //            //覆写此方法以改变默认终点图标
    //            return BitmapDescriptorFactory.fromResource(R.drawable.map_take_icon);
    //        }
    //
    //        @Override
    //        public boolean onRouteNodeClick(int i) {
    //            // TODO Auto-generated method stub
    //            //覆写此方法以改变默认点击处理
    //            return true;
    //        }
    //    }
    private class MyBikingRouteOverlay extends BikingRouteOverlay {
        /**
         * 构造函数
         *
         * @param baiduMap 该DrivingRouteOvelray引用的 BaiduMap
         */
        public MyBikingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            //覆写此方法以改变默认起点图标
            return BitmapDescriptorFactory.fromResource(R.drawable.map_me);
            //这里可以使用BitmapDescriptorFactory.fromView(view)实现自定义view覆盖物，自定义覆盖物请关注以后的文章。
        }

        @Override
        public Integer getLineColor() {
            // TODO Auto-generated method stub
            //覆写此方法以改变默认绘制颜色
            //Returns:
            //线颜色
            return super.getLineColor();
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            //覆写此方法以改变默认终点图标
            if (Const.CourierTaskStatus.sameCityTask == taskType && type == 1) {
                return BitmapDescriptorFactory.fromResource(R.drawable.map_send_icon);
            } else {
                return BitmapDescriptorFactory.fromResource(R.drawable.map_take_icon);
            }
        }

        @Override
        public boolean onRouteNodeClick(int i) {
            // TODO Auto-generated method stub
            //覆写此方法以改变默认点击处理
            return true;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);

    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (mSearch != null) {
            mSearch.destroy();
        }
        if (mBaiduMap != null) {
            mBaiduMap.clear();
        }
        if (mSearch != null) {
            mSearch.destroy();
        }
        mMapView.onDestroy();
        super.onDestroy();
    }
}
